<?php
namespace app\index\controller;

use app\index\controller\IndexBaseController;
use app\common\lib\Show;
use think\exception\ValidateException;
use app\index\validate\JfUser as JfUserValidate;
use think\Exception;
use app\common\lib\Str;
use think\facade\Cookie;
use think\facade\Cache;

class Login extends IndexBaseController {

  public function index()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求'); 
    }
    $qurey_info = $this->request->param();
    try {
      validate(JfUserValidate::class)->scene('login')->check($qurey_info);
    }catch (ValidateException $validateException){
      return Show::error($validateException->getError());
    }
    try {
      // 对比验证码
      $verifyCode = Cache::store('redis')->get($qurey_info['phone']);
      if (empty($verifyCode)) {
        return Show::error('验证码不存在'); 
      }
      if ($verifyCode !== $qurey_info['verifyCode']) {
        return Show::error('验证码不正确'); 
      }
      // 查找用户信息
      $userInfo = $this->jf_user_model->getJfUserByPhone($qurey_info['phone']);
      if (empty($userInfo)){
        // 用户不存在，需要创建新用户
        $newJfUserInfo = [
          'username' => Str::getUsername(),
          'nickname' => Str::getNickname(),
          'phone' => $qurey_info['phone'],
          'avatar' => '/upload/pic/20210529/64c58d26a6c002511d8723a6f3ebbd1f.jpg',
        ];
        $this->jf_user_model->save($newJfUserInfo);
        $userInfo = $this->jf_user_model->getJfUserByPhone($qurey_info['phone']);
      }
      Cookie::set('jf_user_info', $userInfo, 7*24*60*60);
      return Show::success($userInfo); 
    } catch (Exception $e) {
      return Show::error($e->getMessage());
    }
  }
  public function sendVerifyCode()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求'); 
    }
    $qurey_info = $this->request->param();
    // 存储登陆信息
    $verifyCode = Str::getVerifyCode();
    Cache::store('redis')->set($qurey_info['phone'],$verifyCode, 60000);
    return Show::success($verifyCode); 
  }
}
